import React from "react";
import { Input, Modal, Icon, Button, message } from "antd";
import { connect } from "dva";

class TabPaneModal extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			visible: false,
			tabPaneList: [],
		};
	}

	componentDidMount() {
		if (this.props.onRef) {
			this.props.onRef(this);
		}
	}

	/**
	 * 打开modal并初始化数据
	 * @returns {*}
	 */
	openModal = (tabPaneList) => {
		this.setState({
			visible: true,
			tabPaneList,
		});
	};

	/**
	 * 关闭modal
	 * @returns {*}
	 */
	closeModal = () => {
		this.setState({ visible: false }, () => {
			this.props.getTabList();
		});
	};

	/**
	 * 新增分类
	 * @returns {*}
	 */
	addTabPane = () => {
		let { tabPaneList } = this.state;
		tabPaneList.push({ id: "", name: "" });
		this.setState({ tabPaneList });
	};

	/**
	 * 移除分类
	 * @returns {*}
	 */
	removeTabPane = (index) => {
		const { tabPaneList } = this.state;
		const arr = tabPaneList.filter((item, i) => index != i);
		this.setState({ tabPaneList: arr });
	};

	/**
	 * input改变
	 * @returns {*}
	 */
	changeName = (e, index) => {
		let { tabPaneList } = this.state;
		tabPaneList[index].name = e.target.value;
		this.setState({ tabPaneList });
	};

	/**
	 * 确定
	 * @returns {*}
	 */
	updateCategory = () => {
		const { tabPaneList } = this.state;
		const { dispatch, id } = this.props;
		dispatch({
			type: "dialogLists/editDialogCategory",
			payload: {
				categoryList: tabPaneList,
				categoryId: id,
			},
			callback: (res) => {
				if (typeof res.code !== 'undefined' && res.code !== 0) {
					// message["error"](`${res.message}`);
				} else {
					console.log(res);
					message.info(res.message);
					this.closeModal();
				}
			},
		});
	};

	render() {
		const { visible, tabPaneList } = this.state;
		return (
			<Modal title={"分类管理"} visible={visible} onCancel={this.closeModal} onOk={this.updateCategory}>
				<div>
					{tabPaneList.map((item, index) => {
						return (
							<div key={index} style={{ margin: "5px" }}>
								<Input
									value={item.name}
									style={{ width: "85%" }}
									onChange={(e) => this.changeName(e, index)}
								/>
								<Icon
									type='close'
									style={{ marginLeft: 10 }}
									onClick={() => this.removeTabPane(index)}
								/>
							</div>
						);
					})}
				</div>
				<Button icon={"plus"} type={"link"} onClick={this.addTabPane}>添加分类</Button>
			</Modal>
		);
	}
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(TabPaneModal);
